import { generateKey, isFunction, getTime } from "../utils";

// 储存时存入当前时间和有效期
const set = (
  key,
  value,
  time,
  { separator, group, isJson, customSetItem, getCustomTime } = {}
) => {
  const _key = generateKey(key, { separator, group });
  const _obj = {
    value,
    time: time || 0,
    currentTime: getTime(isFunction(getCustomTime) && getCustomTime()),
  };
  const _value = isJson === false ? _obj : JSON.stringify(_obj);
  if (isFunction(customSetItem)) {
    customSetItem(_key, _value);
  }
};

// 取出时计算是否超时，超时返回null
const get = (
  key,
  {
    separator,
    group,
    isJson,
    customGetItem,
    customRemoveItem,
    getCustomTime,
  } = {}
) => {
  let content = null;
  const _key = generateKey(key, { separator, group });
  if (isFunction(customGetItem)) {
    content =
      isJson === false ? customGetItem(_key) : JSON.parse(customGetItem(_key));
  }
  if (content) {
    const gapTime =
      getTime(isFunction(getCustomTime) && getCustomTime()) -
      content.currentTime;
    if (content.time === 0 || gapTime <= content.time) {
      return content.value;
    } else {
      // 删除缓存的内容
      if (isFunction(customRemoveItem)) {
        customRemoveItem(_key);
      }
      return null;
    }
  } else {
    return null;
  }
};

// 删除方法
const remove = (key, { separator, group, customRemoveItem } = {}) => {
  // 删除缓存的内容
  if (isFunction(customRemoveItem)) {
    const _key = generateKey(key, { separator, group });
    customRemoveItem(_key);
  }
};

// 清空方法
const clear = (keys = [], { separator, group, customRemoveItem } = {}) => {
  if (isFunction(customRemoveItem)) {
    keys.forEach((key) => {
      if (new RegExp(`${separator}${group || ""}$`).test(key)) {
        customRemoveItem(key);
      }
    });
  }
};

export default (options) => {
  return {
    setItem: (key, value, time) => set(key, value, time, options),
    getItem: (key) => get(key, options),
    removeItem: (key) => remove(key, options),
    clear: (keys) => clear(keys, options),
  };
};
